package com.wsoft.system.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.utils.EmailUtil;
import com.wsoft.core.vo.MemberVO;
import com.wsoft.enums.TemplateTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 入职周年 定时
 *
 * @Author z001
 * @Date 2024/12/23 11:15
 */
@Slf4j
@Service
public class EntryAnniversaryJob implements Job {

    @Resource
    private CommonMemberService memberService;
    @Resource
    private EmailUtil emailUtil;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<MemberVO> list = memberService.getMemberList();

        List<MemberVO> collect = list.stream().filter(item -> null != item.getEntryTime() && StrUtil.isNotBlank(item.getEmail())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            collect.forEach(user -> {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                String name = user.getName();
                //入职时间
                String hireDateStr = user.getEntryTime().toString();

                // 解析入职日期
                LocalDate hireDate = LocalDate.parse(hireDateStr, formatter);

                // 检查是否是入职周年
                if (hireDate.getMonth() == LocalDate.now().getMonth() && hireDate.getDayOfMonth() == LocalDate.now().getDayOfMonth()) {
                    int yearsOfService = LocalDate.now().getYear() - hireDate.getYear();
                    String bless = generate(name, yearsOfService);
                    emailUtil.sendEmail(user.getEmail(),
                            "入职周年",
                            bless,
                            TemplateTypeEnum.TEXT.getCode());
                }

            });
        }

    }

    /**
     * 周年祝福
     *
     * @param name
     * @param yearsOfService
     * @return
     */
    public static String generate(String name, int yearsOfService) {
        return name + "，恭喜您入职" + yearsOfService + "周年！感谢您一直以来的辛勤付出，祝您在未来的工作中再创佳绩！";
    }

}
